from comtypes.tools.codegenerator.codegenerator import logger
from fastapi import FastAPI

from . import middlewares
from .middlewares.exception import register_exception_handlers
from .middlewares.jwt_middleware import JWTAuthMiddleware
from .middlewares.api_key_middleware import ApiKeyToUserMiddleware
from .router import all_routers_meta
from src.utils.logger import get_logger
import config
from src.common import events
logger = get_logger("capcut")
def create_api_app() -> FastAPI:
    """
    创建并配置API应用

    Args:
        version: API版本号，用于URL路径前缀

    Returns:
        配置完成的FastAPI应用实例
    """

    # 创建 FastAPI 应用
    app = FastAPI(
        title="剪映自动化接口服务",
        version="1.0",
        description="剪映自动化接口服务",
        docs_url="/docs" if config.ENABLE_DOCS else None,
        redoc_url="/redoc" if config.ENABLE_REDOC else None,
        openapi_url="/openapi.json" if config.ENABLE_DOCS else None
    )


    
  
        # 注册JWT认证中间件（在日志中间件之后）
    app.add_middleware(JWTAuthMiddleware)
    app.middleware("http")(middlewares.SimpleLoggingMiddleware)
    app.add_middleware(ApiKeyToUserMiddleware)
    # 注册异常处理
    register_exception_handlers(app)
    # 注册事件处理器
    events.init_app_events(app)
    # 注册所有路由
    for router_meta in all_routers_meta:
        # 合并公共依赖项和路由特定依赖项
        # all_dependencies = COMMON_DEPENDENCIES + router_meta.dependencies

        app.include_router(
            router_meta.router,
            prefix=f"{router_meta.prefix}",
            tags=  router_meta.tags,
            # dependencies=all_dependencies
        )
        logger.info(f"已注册路由: {router_meta.tags} -> {router_meta.prefix}")

    logger.info(f"API应用创建完成")
    return app


# 导出公共接口
__all__ = ["create_api_app"]